package com.lucian.ge.user.controller;

import com.alibaba.fastjson.JSON;
import com.lucian.ge.comman.model.ResultMap;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lucian.ge.user.mapper.UserMapper;
import com.lucian.ge.user.model.User;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

/**
 * Created by Lucicol on 2019/5/13.
 */
@Api(value = "GVCodeController", description = "图形验证码接口(注册/修改密码)")
@RestController
@RequestMapping("/gvcode")
public class GVCodeController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    DefaultKaptcha defaultKaptcha;

    private final UserMapper userMapper;
    private final ResultMap resultMap;

    @Autowired
    public GVCodeController(UserMapper userMapper, ResultMap resultMap) {
        this.userMapper = userMapper;
        this.resultMap = resultMap;
    }

    @ApiOperation(value="图形验证码参数手机号(注册)", notes="参数手机号")

    @PostMapping("/getcode")
    @ResponseBody
    public ResultMap defaultKaptcha(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) @Valid  GVUser gvuser,  BindingResult result,  HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception{

//        String remoteAddr = httpServletRequest.getRemoteAddr();
//        System.out.println(remoteAddr);

        //      参数校验
        if (result.hasErrors()) {
            return resultMap.fail().code(401).message(result.getFieldError().getDefaultMessage());
        }

        if (userMapper.getPassword(gvuser.getUsername()) != null) {
            return resultMap.fail().code(401).message("该手机号已注册,请直接登录");
        }

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到redis中
            String createText = defaultKaptcha.createText();
            redisTemplate.opsForValue().set(gvuser.getUsername()+"gv", createText, 60 * 5, TimeUnit.SECONDS);

            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
//            BufferedImage challenge = defaultKaptcha.createImage(createText);
//            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return resultMap.fail().code(401).message("错误");
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
//        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
//        httpServletResponse.setHeader("Cache-Control", "no-store");
//        httpServletResponse.setHeader("Pragma", "no-cache");
//        httpServletResponse.setDateHeader("Expires", 0);
//        httpServletResponse.setContentType("image/jpeg");
//        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
//        responseOutputStream.write(captchaChallengeAsJpeg);
//        responseOutputStream.flush();
//        responseOutputStream.close();

        return resultMap.success().code(200).message("获取成功");
    }

    @ApiOperation(value="图形验证码参数手机号(修改密码)", notes="参数手机号")

    @PostMapping("/changepassword")
    @ResponseBody
    public ResultMap changepasswordtKaptcha(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) @Valid  GVUser gvuser,  BindingResult result,  HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception{

        //      参数校验
        if (result.hasErrors()) {
            return resultMap.fail().code(401).message(result.getFieldError().getDefaultMessage());
        }

        if (userMapper.getPassword(gvuser.getUsername()) == null) {
            return resultMap.fail().code(401).message("该手机号未注册,请直接注册");
        }

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到redis中
            String createText = defaultKaptcha.createText();
            redisTemplate.opsForValue().set(gvuser.getUsername()+"gv", createText, 60 * 5, TimeUnit.SECONDS);

        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return resultMap.fail().code(401).message("错误");
        }
        return resultMap.success().code(200).message("获取成功");
    }

    @GetMapping("/img")
    @ResponseBody
    public void imgKaptcha(@RequestParam String username, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception{
//        验证码过期
//        if (redisTemplate.opsForValue().get(username)+"gv" == null) {
//            return resultMap.fail().code(401).message("图形验证码过期请刷新");
//        }

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //redis取出code
            String createText = redisTemplate.opsForValue().get(username+"gv");

            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
//            return resultMap.fail().code(401).message("错误");
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();

//        return resultMap.success().code(200).message("成功");
    }
}

@ApiModel
class GVUser {
    @ApiModelProperty(value = "手机号")
    @NotEmpty(message="手机号不能为空")
    @Pattern(regexp = "1[3|4|5|7|8][0-9]\\d{8}",message="手机号格式错误")
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

